<template>
    <div class="class-manage">
        <el-breadcrumb separator="/" class="header">
            <el-breadcrumb-item>班级管理</el-breadcrumb-item>
        </el-breadcrumb>

        <el-form :model="searchParams" class="function-area-form" inline>
            <!-- 班级名称筛选项 -->
            <el-form-item label="班级名称" class="filter-form-item">
                <el-input v-model="searchParams.className" placeholder="请输入班级名称" class="filter-input"
                    @keyup.enter="handleFilter" />
            </el-form-item>

            <!-- 课程名称筛选项 -->
            <el-form-item label="课程名称" class="filter-form-item">
                <el-input v-model="searchParams.courseName" placeholder="请输入课程名称" class="filter-input"
                    @keyup.enter="handleFilter" />
            </el-form-item>

            <!-- 带班老师筛选项 -->
            <el-form-item label="带班老师" class="filter-form-item">
                <el-select v-model="searchParams.teacherName" placeholder="请选择" clearable class="filter-select"
                    @change="handleFilter">
                    <el-option label="全部" value="" />
                    <el-option v-for="teacher in teacherList" :key="teacher.id" :label="teacher.teacherName"
                        :value="teacher.teacherName" />
                </el-select>
            </el-form-item>

            <!-- 班级状态筛选项 -->
            <el-form-item label="班级状态" class="filter-form-item">
                <el-select v-model="searchParams.classStatus" placeholder="请选择" clearable class="filter-select"
                    @change="handleFilter">
                    <el-option label="全部" value="" />
                    <el-option label="学习中" value="学习中" />
                    <el-option label="毕业" value="毕业" />
                </el-select>
            </el-form-item>
        </el-form>

        <div class="filter-actions">
            <div class="filter-actions-left">
                <el-button type="primary" @click="handleFilter" :icon="Search">筛选</el-button>
                <el-button @click="resetFilter" :icon="Refresh">重置</el-button>
            </div>

            <el-button type="primary" @click="handleAdd" :icon="Plus">新增班级</el-button>
        </div>

        <el-table border :data="classList" style="width: 100%" height="calc(100vh - 300px)" :fit="true" v-loading="loading"
            empty-text="暂无班级数据" highlight-current-row>
            <el-table-column type="index" label="#" width="60" align="center" />
            <el-table-column label="班级名称" align="center">
                <template #default="scope">
                    <el-link underline="never" type="primary" @click="gotoClassDetail(scope.row)">
                        {{ scope.row.className }}
                    </el-link>
                </template>
            </el-table-column>
            <el-table-column label="带班老师" prop="teacherName" align="center" />
            <el-table-column label="课程名称" prop="courseName" align="center" />
            <el-table-column label="班级人数" prop="classSize" align="center">
                <template #default="scope">
                    {{ scope.row.classSize }}人
                </template>
            </el-table-column>
            <el-table-column label="价格" prop="price" align="center" />
            <el-table-column label="班级状态" align="center">
                <template #default="scope">
                    <el-tag :type="scope.row.classStatus === '学习中' ? 'success' : 'info'">
                        {{ scope.row.classStatus }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="200">
                <template #default="scope">
                    <el-button size="small" type="info" @click="handleEdit(scope.row)">修改</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row.classId)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <div class="pagination-container">
            <el-pagination background v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
                layout="prev, pager, next" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 新增/编辑对话框 -->
        <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px" @close="resetForm">
            <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
                <el-form-item label="班级名称" prop="className" required>
                    <el-input v-model="form.className" placeholder="请输入班级名称" clearable />
                </el-form-item>

                <el-form-item label="带班老师" prop="teacherId">
                    <el-select v-model="form.teacherId" placeholder="请选择" style="width: 100%">
                        <el-option v-for="teacher in teacherList" :key="teacher.id" :label="teacher.teacherName"
                            :value="teacher.id" />
                    </el-select>
                </el-form-item>

                <el-form-item label="开班时间" prop="startTime" required>
                    <el-date-picker v-model="form.startTime" type="date" placeholder="选择日期" style="width: 100%"
                        value-format="YYYY-MM-DD" />
                </el-form-item>

                <el-form-item label="课程名称" prop="courseId">
                    <el-button type="primary" @click="courseDialogVisible = true">选择课程</el-button>
                    <span v-if="form.courseName" class="selected-course ml-2">{{ form.courseName }}</span>
                    <el-input v-model="form.courseId" type="hidden" />
                </el-form-item>

                <el-form-item label="课程价格" prop="price">
                    <el-input-number v-model="form.price" :min="0" placeholder="请输入价格" controls-position="right"
                        style="width: 100%" />
                </el-form-item>

                <el-form-item label="班级类别" prop="type">
                    <el-select v-model="form.type" placeholder="请选择" style="width: 100%">
                        <el-option label="前端" value="前端" />
                        <el-option label="AI训练师" value="AI训练师" />
                    </el-select>
                </el-form-item>

                <el-form-item label="班级状态" prop="classStatus" required>
                    <el-select v-model="form.classStatus" placeholder="请选择" style="width: 100%">
                        <el-option label="学习中" value="学习中" />
                        <el-option label="毕业" value="毕业" />
                    </el-select>
                </el-form-item>

                <el-form-item label="班级备注" prop="remarks">
                    <el-input v-model="form.remarks" type="textarea" :rows="3" placeholder="请输入班级备注" />
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 课程选择对话框 -->
        <el-dialog title="选择课程" v-model="courseDialogVisible" width="800px">
            <el-form :model="courseSearchParams" class="mb-3" inline>
                <el-form-item label="课程名称">
                    <el-input v-model="courseSearchParams.courseName" placeholder="请输入课程名称"
                        @keyup.enter="fetchCourseList" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="fetchCourseList" :icon="Search">搜索</el-button>
                    <el-button @click="resetCourseFilter" :icon="Refresh">重置</el-button>
                </el-form-item>
            </el-form>

            <el-table border :data="courseList" style="width: 100%" height="400" highlight-current-row>
                <el-table-column type="index" label="#" width="60" align="center" />
                <el-table-column label="课程名称" prop="courseName" align="center" />
                <el-table-column label="创建时间" align="center">
                    <template #default="scope">
                        {{ formatCreateTime(scope.row.createTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="课程状态" align="center">
                    <template #default="scope">
                        <el-tag :type="courseStatusMap.type(scope.row.status)">
                            {{ courseStatusMap.label(scope.row.status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="120">
                    <template #default="scope">
                        <el-button size="small" type="primary" @click="handleSelectCourse(scope.row)">选择</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- <div class="pagination-container mt-3">
                <el-pagination background v-model:current-page="courseCurrentPage" v-model:page-size="coursePageSize"
                    :total="courseTotal" layout="prev, pager, next" @size-change="handleCourseSizeChange"
                    @current-change="handleCourseCurrentChange" />
            </div> -->
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { getClassList, getTeacherList, delClassInfo, addClassInfo, updateClassInfo } from '../../../api/class/class'
import { getCourseBaseInfo } from '../../../api/consultant/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 班级列表相关变量
const classList = ref([])
const teacherList = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 搜索参数
const searchParams = ref({
    className: '',
    courseName: '',
    teacherName: '',
    classStatus: ''
})

// 对话框相关变量
const dialogVisible = ref(false)
const submitting = ref(false)
const formRef = ref()

// 表单数据
const form = reactive({
    classId: '',
    className: '',
    teacherId: '',
    startTime: '',
    courseId: '',
    courseName: '',
    price: '0',
    type: '',
    classStatus: '',
    remarks: ''
})

// 表单验证规则
const rules = reactive({
    className: [{ required: true, message: '请输入班级名称', trigger: 'blur' }],
    startTime: [{ required: true, message: '请选择开班时间', trigger: 'change' }],
    classStatus: [{ required: true, message: '请选择班级状态', trigger: 'change' }]
})

// 计算对话框标题
const dialogTitle = computed(() => {
    return form.classId ? '编辑班级' : '新增班级'
})

// 课程选择相关变量
const courseDialogVisible = ref(false)
const courseList = ref([])
const courseTotal = ref(0)
const courseCurrentPage = ref(1)
const coursePageSize = ref(10)
const courseSearchParams = ref({
    courseName: ''
})

// 格式化创建时间
const formatCreateTime = (time) => {
    if (!time) return '-';
    const [datePart, timePart] = time.split('T');
    const pureTime = timePart.slice(0, 8);
    return `${datePart} ${pureTime}`;
};

// 课程状态映射
const courseStatusMap = computed(() => ({
    label: (status) => status === 1 ? '上架' : '未上架',
    type: (status) => status === 1 ? 'success' : 'danger'
}));

// 跳转到班级详情
const gotoClassDetail = async (classItem) => {
    try {
        const encodedData = encodeURIComponent(JSON.stringify(classItem));
        await router.push(`/xueguan/detail?data=${encodedData}`)
    } catch (err) {
        console.error('路由跳转失败:', err)
        ElMessage.error('页面跳转失败，请稍后重试')
    }
}

// 获取班级数据
const fetchClassData = async () => {
    try {
        loading.value = true

        const params = {
            pageNum: currentPage.value,
            pageSize: pageSize.value,
            ...searchParams.value
        }

        Object.keys(params).forEach(key => {
            if (params[key] === '') {
                delete params[key]
            }
        })

        const res = await getClassList(params)

        if (res.code === 200) {
            classList.value = res.rows
            total.value = res.total
        } else {
            ElMessage.error(res.msg || '获取班级数据失败')
        }
    } catch (error) {
        console.error('获取班级数据出错:', error)
        ElMessage.error('网络错误，获取班级数据失败')
    } finally {
        loading.value = false
    }
}

// 获取教师列表
const fetchTeacherList = async () => {
    try {
        const res = await getTeacherList()
        if (res.code === 200) {
            teacherList.value = res.data || res.rows || []
        }
    } catch (error) {
        console.error('获取教师列表失败:', error)
        ElMessage.error('获取教师列表失败')
    }
}

// 获取课程列表
const fetchCourseList = async () => {
    try {
        const params = {
            pageNum: courseCurrentPage.value,
            pageSize: coursePageSize.value,
            ...courseSearchParams.value
        }

        // 移除空值参数
        Object.keys(params).forEach(key => {
            if (params[key] === '') {
                delete params[key]
            }
        })

        const res = await getCourseBaseInfo(params)
        if (res.code === 200) {
            courseList.value = res.rows || []
            courseTotal.value = res.total || 0
        } else {
            ElMessage.error(res.msg || '获取课程列表失败')
        }
    } catch (error) {
        console.error('获取课程列表出错:', error)
        ElMessage.error('网络错误，获取课程列表失败')
    }
}

// 筛选处理
const handleFilter = () => {
    currentPage.value = 1
    fetchClassData()
}

// 重置筛选
const resetFilter = () => {
    searchParams.value = {
        className: '',
        courseName: '',
        teacherName: '',
        classStatus: ''
    }
    handleFilter()
}

// 分页处理
const handleSizeChange = (val) => {
    pageSize.value = val
    fetchClassData()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchClassData()
}

// 课程选择对话框分页处理
const handleCourseSizeChange = (val) => {
    coursePageSize.value = val
    fetchCourseList()
}

const handleCourseCurrentChange = (val) => {
    courseCurrentPage.value = val
    fetchCourseList()
}

// 重置课程筛选
const resetCourseFilter = () => {
    courseSearchParams.value = {
        courseName: ''
    }
    fetchCourseList()
}

// 选择课程
const handleSelectCourse = (course) => {
    console.log(course);

    form.courseId = course.id
    form.courseName = course.courseName
    courseDialogVisible.value = false
}

// 删除班级
const handleDelete = async (classId) => {
    try {
        await ElMessageBox.confirm('确定要删除这个班级吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        const res = await delClassInfo(classId)
        if (res.code === 200) {
            ElMessage.success('删除成功')
            fetchClassData()
        } else {
            ElMessage.error(res.msg || '删除失败')
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除班级失败:', error)
            ElMessage.error('删除失败')
        }
    }
}

// 编辑班级
const handleEdit = (row) => {
    Object.assign(form, {
        classId: row.classId,
        className: row.className,
        teacherId: row.teacherId,
        startTime: row.startTime,
        courseId: row.courseId,
        courseName: row.courseName,
        price: row.price,
        type: row.type,
        classStatus: row.classStatus,
        remarks: row.remarks || ''
    })
    dialogVisible.value = true
}

// 新增班级
const handleAdd = () => {
    resetForm()
    dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
    if (formRef.value) {
        formRef.value.resetFields()
    }
    Object.assign(form, {
        classId: '',
        className: '',
        teacherId: '',
        startTime: '',
        courseId: '',
        courseName: '',
        price: '0',
        type: '',
        classStatus: '',
        remarks: ''
    })
}

// 提交表单
const handleSubmit = async () => {
    try {
        await formRef.value.validate()

        submitting.value = true

        let res
        if (form.classId) {
            res = await updateClassInfo(form)
        } else {
            res = await addClassInfo(form)
        }

        if (res.code === 200) {
            ElMessage.success(form.classId ? '更新成功' : '新增成功')
            dialogVisible.value = false
            fetchClassData()
        } else {
            ElMessage.error(res.msg || (form.classId ? '更新失败' : '新增失败'))
        }
    } catch (error) {
        console.error('提交表单失败:', error)
        if (error !== 'cancel') {
            ElMessage.error('操作失败，请重试')
        }
    } finally {
        submitting.value = false
    }
}

onMounted(() => {
    fetchClassData()
    fetchTeacherList()
    fetchCourseList()
})
</script>

<style scoped>
.class-manage {
    width: 100%;
    overflow-x: auto;
    box-sizing: border-box;
}

.header {
    padding: 15px 0;
    font-size: 20px;
    color: #333;
}

.function-area-form {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-bottom: 20px;
    flex-wrap: wrap;
}

.filter-form-item {
    width: 25%;
    margin-right: 0;
    margin-bottom: 0;
}

.filter-input {
    width: 200px;
}

.filter-select {
    width: 200px;
}

.filter-actions {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
}

.filter-actions-left {
    display: flex;
    gap: 10px;
}

:deep(.el-table__row:hover) {
    background-color: #f5f7fa !important;
}

:deep(.el-table__header th) {
    background-color: #f9fafb;
    font-weight: 500;
    color: #666;
}

.pagination-container {
    margin-top: 20px;
    text-align: right;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.el-link {
    font-weight: 500;
}

.el-link:hover {
    text-decoration: none;
}

.selected-course {
    color: #165DFF;
    font-weight: 500;
}

.mt-3 {
    margin-top: 15px;
}

.mb-3 {
    margin-bottom: 15px;
}

.ml-2 {
    margin-left: 10px;
}
</style>
